<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>处理 Null 值 | Elasticsearch: 权威指南 | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch: 权威指南">
<link rel="up" href="structured-search.html" title="结构化搜索">
<link rel="prev" href="_ranges.html" title="范围">
<link rel="next" href="filter-caching.html" title="关于缓存">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Definitive Guide">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="2.x">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="zh_cn">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<b>请注意:</b><br>本书基于 Elasticsearch 2.x 版本，有些内容可能已经过时。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch: 权威指南</a></span>
»
<span class="breadcrumb-link"><a href="search-in-depth.html">深入搜索</a></span>
»
<span class="breadcrumb-link"><a href="structured-search.html">结构化搜索</a></span>
»
<span class="breadcrumb-node">处理 Null 值</span>
</div>
<div class="navheader">
<span class="prev">
<a href="_ranges.html">« 范围</a>
</span>
<span class="next">
<a href="filter-caching.html">关于缓存 »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="_dealing_with_null_values"></a>处理 Null 值<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/080_Structured_Search/30_existsmissing.asciidoc">edit</a>
</h2>
</div></div></div>
<p>回想在之前例子中，有的文档有名为 <code class="literal">tags</code> （标签）的字段，它是个多值字段，一个文档可能有一个或多个标签，也可能根本就没有标签。如果一个字段没有值，那么如何将它存入倒排索引中的呢？</p>
<p>这是个有欺骗性的问题，因为答案是：什么都不存。让我们看看之前内容里提到过的倒排索引：</p>
<div class="informaltable">
<table border="1" cellpadding="4px" width="50%">
<colgroup>
<col class="col_1">
<col class="col_2">
</colgroup>
<tbody>
<tr>
<td align="left" valign="top"><p>Token</p></td>
<td align="left" valign="top"><p>DocIDs</p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">open_source</code></p></td>
<td align="left" valign="top"><p><code class="literal">2</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">search</code></p></td>
<td align="left" valign="top"><p><code class="literal">1</code>,<code class="literal">2</code></p></td>
</tr>
</tbody>
</table>
</div>
<p>如何将某个不存在的字段存储在这个数据结构中呢？无法做到！简单的说，一个倒排索引只是一个 token 列表和与之相关的文档信息，如果字段不存在，那么它也不会持有任何 token，也就无法在倒排索引结构中表现。</p>
<p>最终，这也就意味着，<code class="literal">null</code>, <code class="literal">[]</code> （空数组）和 <code class="literal">[null]</code> 所有这些都是等价的，它们无法存于倒排索引中。</p>
<p>显然，世界并不简单，数据往往会有缺失字段，或有显式的空值或空数组。为了应对这些状况，Elasticsearch 提供了一些工具来处理空或缺失值。</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_存在查询"></a>存在查询<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/080_Structured_Search/30_existsmissing.asciidoc">edit</a>
</h3>
</div></div></div>
<p>第一件武器就是 <code class="literal">exists</code> 存在查询。这个查询会返回那些在指定字段有任何值的文档，让我们索引一些示例文档并用标签的例子来说明：</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">POST /my_index/posts/_bulk
{ "index": { "_id": "1"              }}
{ "tags" : ["search"]                }  <a id="CO53-1"></a><i class="conum" data-value="1"></i>
{ "index": { "_id": "2"              }}
{ "tags" : ["search", "open_source"] }  <a id="CO53-2"></a><i class="conum" data-value="2"></i>
{ "index": { "_id": "3"              }}
{ "other_field" : "some data"        }  <a id="CO53-3"></a><i class="conum" data-value="3"></i>
{ "index": { "_id": "4"              }}
{ "tags" : null                      }  <a id="CO53-4"></a><i class="conum" data-value="4"></i>
{ "index": { "_id": "5"              }}
{ "tags" : ["search", null]          }  <a id="CO53-5"></a><i class="conum" data-value="5"></i></pre>
</div>
<div class="sense_widget" data-snippet="snippets/080_Structured_Search/30_Exists_missing.json"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO53-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">tags</code> 字段有 1 个值。</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO53-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">tags</code> 字段有 2 个值。</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO53-3"><i class="conum" data-value="3"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">tags</code> 字段缺失。</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO53-4"><i class="conum" data-value="4"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">tags</code> 字段被置为 <code class="literal">null</code> 。</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO53-5"><i class="conum" data-value="5"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">tags</code> 字段有 1 个值和 1 个 <code class="literal">null</code> 。</p>
</td>
</tr>
</table>
</div>
<p>以上文档集合中 <code class="literal">tags</code> 字段对应的倒排索引如下：</p>
<div class="informaltable">
<table border="1" cellpadding="4px" width="50%">
<colgroup>
<col class="col_1">
<col class="col_2">
</colgroup>
<tbody>
<tr>
<td align="left" valign="top"><p>Token</p></td>
<td align="left" valign="top"><p>DocIDs</p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">open_source</code></p></td>
<td align="left" valign="top"><p><code class="literal">2</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">search</code></p></td>
<td align="left" valign="top"><p><code class="literal">1</code>,<code class="literal">2</code>,<code class="literal">5</code></p></td>
</tr>
</tbody>
</table>
</div>
<p>我们的目标是找到那些被设置过标签字段的文档，并不关心标签的具体内容。只要它存在于文档中即可，用 SQL 的话就是用 <code class="literal">IS NOT NULL</code> 非空进行查询：</p>
<div class="pre_wrapper lang-sql">
<pre class="programlisting prettyprint lang-sql">SELECT tags
FROM   posts
WHERE  tags IS NOT NULL</pre>
</div>
<p>在 Elasticsearch 中，使用 <code class="literal">exists</code> 查询的方式如下：</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">GET /my_index/posts/_search
{
    "query" : {
        "constant_score" : {
            "filter" : {
                "exists" : { "field" : "tags" }
            }
        }
    }
}</pre>
</div>
<div class="sense_widget" data-snippet="snippets/080_Structured_Search/30_Exists_missing.json"></div>
<p>这个查询返回 3 个文档：</p>
<div class="pre_wrapper lang-json">
<pre class="programlisting prettyprint lang-json">"hits" : [
    {
      "_id" :     "1",
      "_score" :  1.0,
      "_source" : { "tags" : ["search"] }
    },
    {
      "_id" :     "5",
      "_score" :  1.0,
      "_source" : { "tags" : ["search", null] } <a id="CO54-1"></a><i class="conum" data-value="1"></i>
    },
    {
      "_id" :     "2",
      "_score" :  1.0,
      "_source" : { "tags" : ["search", "open source"] }
    }
]</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO54-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>尽管文档 5 有 <code class="literal">null</code> 值，但它仍会被命中返回。字段之所以存在，是因为标签有实际值（  <code class="literal">search</code> ）可以被索引，所以 <code class="literal">null</code> 对过滤不会产生任何影响。</p>
</td>
</tr>
</table>
</div>
<p>显而易见，只要 <code class="literal">tags</code> 字段存在项（term）的文档都会命中并作为结果返回，只有 3 和 4 两个文档被排除。</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_缺失查询"></a>缺失查询<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/080_Structured_Search/30_existsmissing.asciidoc">edit</a>
</h3>
</div></div></div>
<p>这个 <code class="literal">missing</code> 查询本质上与 <code class="literal">exists</code> 恰好相反：它返回某个特定 <em>无</em> 值字段的文档，与以下 SQL 表达的意思类似：</p>
<div class="pre_wrapper lang-sql">
<pre class="programlisting prettyprint lang-sql">SELECT tags
FROM   posts
WHERE  tags IS NULL</pre>
</div>
<p>我们将前面例子中 <code class="literal">exists</code> 查询换成 <code class="literal">missing</code> 查询：</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">GET /my_index/posts/_search
{
    "query" : {
        "constant_score" : {
            "filter": {
                "missing" : { "field" : "tags" }
            }
        }
    }
}</pre>
</div>
<div class="sense_widget" data-snippet="snippets/080_Structured_Search/30_Exists_missing.json"></div>
<p>按照期望的那样，我们得到 3 和 4 两个文档（这两个文档的 <code class="literal">tags</code> 字段没有实际值）：</p>
<div class="pre_wrapper lang-json">
<pre class="programlisting prettyprint lang-json">"hits" : [
    {
      "_id" :     "3",
      "_score" :  1.0,
      "_source" : { "other_field" : "some data" }
    },
    {
      "_id" :     "4",
      "_score" :  1.0,
      "_source" : { "tags" : null }
    }
]</pre>
</div>
<div class="sidebar">
<div class="titlepage"><div><div>
<p class="title"><strong>当 null 的意思是 null</strong></p>
</div></div></div>
<p>有时候我们需要区分一个字段是没有值，还是它已被显式的设置成了 <code class="literal">null</code> 。在之前例子中，我们看到的默认的行为是无法做到这点的；数据被丢失了。不过幸运的是，我们可以选择将显式的 <code class="literal">null</code> 值替换成我们指定 <em>占位符（placeholder）</em> 。</p>
<p>在为字符串（string）、数字（numeric）、布尔值（Boolean）或日期（date）字段指定映射时，同样可以为之设置 <code class="literal">null_value</code> 空值，用以处理显式 <code class="literal">null</code> 值的情况。不过即使如此，还是会将一个没有值的字段从倒排索引中排除。</p>
<p>当选择合适的 <code class="literal">null_value</code> 空值的时候，需要保证以下几点：</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
它会匹配字段的类型，我们不能为一个 <code class="literal">date</code> 日期字段设置字符串类型的 <code class="literal">null_value</code> 。
</li>
<li class="listitem">
它必须与普通值不一样，这可以避免把实际值当成 <code class="literal">null</code> 空的情况。
</li>
</ul>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_对象上的存在与缺失"></a>对象上的存在与缺失<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/080_Structured_Search/30_existsmissing.asciidoc">edit</a>
</h3>
</div></div></div>
<p>不仅可以过滤核心类型， <code class="literal">exists</code> and <code class="literal">missing</code> 查询
 还可以处理一个对象的内部字段。以下面文档为例：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
   "name" : {
      "first" : "John",
      "last" :  "Smith"
   }
}</pre>
</div>
<p>我们不仅可以检查 <code class="literal">name.first</code> 和 <code class="literal">name.last</code> 的存在性，也可以检查 <code class="literal">name</code> ，不过在 <a class="xref" href="mapping.html" title="类型和映射">映射</a> 中，如上对象的内部是个扁平的字段与值（field-value）的简单键值结构，类似下面这样：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
   "name.first" : "John",
   "name.last"  : "Smith"
}</pre>
</div>
<p>那么我们如何用 <code class="literal">exists</code> 或 <code class="literal">missing</code> 查询 <code class="literal">name</code> 字段呢？ <code class="literal">name</code> 字段并不真实存在于倒排索引中。</p>
<p>原因是当我们执行下面这个过滤的时候：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "exists" : { "field" : "name" }
}</pre>
</div>
<p>实际执行的是：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "bool": {
        "should": [
            { "exists": { "field": "name.first" }},
            { "exists": { "field": "name.last" }}
        ]
    }
}</pre>
</div>
<p>这也就意味着，如果 <code class="literal">first</code> 和 <code class="literal">last</code> 都是空，那么 <code class="literal">name</code> 这个命名空间才会被认为不存在。</p>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="_ranges.html">« 范围</a>
</span>
<span class="next">
<a href="filter-caching.html">关于缓存 »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
